package com.study.cloud.apilog.request;

import com.alibaba.fastjson.JSON;
import com.study.cloud.apilog.GatewayApiLog;
import com.study.cloud.utils.TraceIdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @Date 2022/5/17
 * @Author Cliff
 * desc
 */
public abstract class AbstractRequestBody implements RequestBodyService{

    private Logger logger = LoggerFactory.getLogger(SimpleRequestBodyImpl.class);

    @Override
    public BodyWrapper handler(ServerWebExchange exchange) {

        // 初始日志实体对象
        GatewayApiLog gatewayApiLog = initGatewayApiLog(exchange);

        // 获取返回对象
        BodyWrapper requestBody = getRequestBody(exchange, gatewayApiLog);
        requestBody.setGatewayApiLog(gatewayApiLog);
        return requestBody;
    }

    /**
     * 初始化日志对象
     * @param exchange
     * @return
     */
    private GatewayApiLog initGatewayApiLog(ServerWebExchange exchange) {

        GatewayApiLog gatewayLog = new GatewayApiLog();
        // 获取路由信息
        Route route = getGatewayRoute(exchange);
        ServerHttpRequest request = exchange.getRequest();
        String traceId = request.getHeaders().get(TraceIdUtil.TRACE_ID).get(0);
        gatewayLog.setTraceId(traceId);
        gatewayLog.setRequestMethod(request.getMethodValue());
        gatewayLog.setTargetServer(route.getUri().toString());
        gatewayLog.setTimeStart(LocalDateTime.now());
        Map<String, Object> headers = new HashMap<>();
        for (String key : request.getHeaders().keySet()) {
            headers.put(key, request.getHeaders().getFirst(key));
        }
        gatewayLog.setHeaders(JSON.toJSONString(headers));
        if (request.getHeaders().getContentType() != null) {
            gatewayLog.setRequestContentType(request.getHeaders().getContentType().toString());
        }
        return gatewayLog;
    }

    /**
     * 获取路由信息
     * @param exchange
     * @return
     */
    private Route getGatewayRoute(ServerWebExchange exchange) {
        return exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
    }

    public abstract BodyWrapper getRequestBody(ServerWebExchange exchange, GatewayApiLog gatewayLog);



}
